package org.joyflow.core.instance;


import cn.hutool.extra.spring.SpringUtil;
import org.joyflow.core.entity.DbType;
import org.joyflow.core.meta.H2DatabaseMeta;
import org.joyflow.core.service.SpringDbService;
import org.joyflow.core.meta.DatabaseInterface;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DbTypeRegistry {
    private static final DbTypeRegistry instance = new DbTypeRegistry();
    private static List<DbType> types = new ArrayList<>();
    private static Map<String, DatabaseInterface> allDatabseInterfaces = new HashMap<>();

    private DbTypeRegistry() {

    }

    public static DbTypeRegistry instance() {
        return instance;
    }

    public static void init() {
        SpringDbService dbService = SpringUtil.getBean(SpringDbService.class);
        types = dbService.getDatabaseTypes();
    }

    public List<DbType> getTypes() {
        return types;
    }

    public static Map<String, DatabaseInterface> getDatabaseInterfacesMap() {
        if (allDatabseInterfaces.isEmpty()) {
            //初始化
            allDatabseInterfaces.put("H2", new H2DatabaseMeta());
        }
        return allDatabseInterfaces;
    }

    public static DatabaseInterface findDatabaseInterface(String code) {
        try {
            return (DatabaseInterface)DbTypeRegistry.getDatabaseInterfacesMap().get(code).clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }

    public String getTypeCode(Serializable dbTypeId) {
        for (DbType type : types) {
            if (type.getId().equals(dbTypeId)) {
                return type.getCode();
            }
        }
        return null;
    }

}
